app.controller('perfectinfoPageCtrl', function($scope, $cordovaCamera, PopupService, $http, $myconfig, $state, $stateParams, $ionicLoading, ionicDatePicker, $ionicConfig, $mydialog) {


    // console.log($stateParams.next);
    $scope.useMes = JSON.parse($stateParams.next);
    $scope.useMes.wxinfo = JSON.parse(localStorage.getItem('wxinfo'));
    //选择用户性别
    $scope.openSex = function() {
        PopupService.popSex($scope);
    };
    //选择用户头像
    $scope.openCam = function() {
        PopupService.CameraS($scope);
    };

    //执行拍照功能
    $scope.camPlay = function(cam) {
        document.addEventListener("deviceready", function() {

            //照片相机参数
            var options = {
                quality: 80, //保存的图像质量，范围为0 - 100
                destinationType: Camera.DestinationType.DATA_URL, //	返回值格式
                sourceType: cam, //设置图片来源
                //  Camera.PictureSourceType.CAMERA,
                MediaType: 0,
                allowEdit: true, //	选择图片前是否允许编辑
                encodingType: Camera.EncodingType.JPEG, //	JPEG = 0, PNG = 1
                targetWidth: 100, //缩放图像的宽度（像素）
                targetHeight: 100, //缩放图像的高度（像素）
                popoverOptions: CameraPopoverOptions, //	iOS,iPad弹出位置
                saveToPhotoAlbum: false, //是否保存到相册
                correctOrientation: true //设置摄像机拍摄的图像是否为正确的方向
            };

            $cordovaCamera.getPicture(options).then(function(imageData) {
                //成功后回调函数，将图片预览至手机，并保存64位地址至本地
                var image = document.getElementById('myImage');
                image.src = "data:image/jpeg;base64," + imageData;
                // $scope.useMes.headimgurl = image.src;
                // console.log( $scope.useMes.headimgurl);
                putb64(image.src, function() {
                        $ionicLoading.hide();
                    })
                    // Setup the loader
                    //  console.log('执行加载动作')
                $ionicLoading.show({
                    content: '图片上传中，请稍后。。。',
                    animation: 'fade-in',
                    showBackdrop: false,
                    maxWidth: 200,
                    showDelay: 0
                });
            }, function(err) {
                // error
            });

        }, false);
    };




    /*通过base64编码字符流计算文件流大小函数*/
    function fileSize(str) {
        var fileSize;
        if (str.indexOf('=') > 0) {
            var indexOf = str.indexOf('=');
            str = str.substring(0, indexOf); //把末尾的’=‘号去掉
        }

        fileSize = parseInt(str.length - (str.length / 8) * 2);
        return fileSize;
    }
    //七牛64位图片上传
    function putb64(base64, callback) {
        $http.get($myconfig.api.base_host + '/qn/token/header')
            .then(function(res) {
                // console.log(res);
                var pic = base64.split(',')[1];
                var url = 'http://up.qiniu.com/putb64/' + fileSize(pic) + '/key/' + res.data.key;
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4) {
                            // console.log('关闭加载动作')
                            callback(JSON.parse(xhr.responseText)); //回调返回的数据
                            // console.log(JSON.parse(xhr.response).key);
                            $scope.useMes.headimgurl = JSON.parse(xhr.response).key;
                        }

                    }
                    // console.log(pic);
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-Type', 'application/octet-stream');
                xhr.setRequestHeader('Authorization', 'UpToken ' + res.data.token);
                xhr.send(pic);
            });
    };




    //     var options = {
    //       destinationType: Camera.DestinationType.FILE_URI,
    //       sourceType: Camera.PictureSourceType.CAMERA,
    //     };

    //     $cordovaCamera.getPicture(options).then(function(imageURI) {
    //       var image = document.getElementById('myImage');
    //       image.src = imageURI;
    //     }, function(err) {
    //       // error
    //     });


    //     // $cordovaCamera.cleanup().then(...); // only for FILE_URI

    //   }, false);



    //设置用户生日
    //设置插件初始设置
    var datePickerObj = {
        // 插件选择完成后回掉方法
        callback: function(val) { //Mandatory
            // console.log('Return value from the datepicker popup is : ' + val, new Date(val));
            // console.log(val);
            $scope.useMes.birthday = val;
        },
        inputDate: new Date(),
        setLabel: '设置',
        todayLabel: '今天',
        closeLabel: '关闭',
        mondayFirst: false,
        weeksList: ["日", "一", "二", "三", "四", "五", "六"],
        monthsList: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一", "十二"],
        templateType: 'popup',
        from: new Date(1900, 1, 1),
        to: new Date(2020, 12, 31),
        showTodayButton: true,
        dateFormat: 'yyyy MM dd',
        closeOnSelect: false,
        disableWeekdays: [7],
    };

    //执行插件选择日期
    $scope.openDatePicker = function() {
        ionicDatePicker.openDatePicker(datePickerObj);
    };






    //选择城市插件  详情参考GitHub ：https://github.com/minh8023/ionic-citypicker
    var vm = $scope.vm = {};
    //   vm.cb = function () {  };

    vm.CityPickData = {
        areaData: ['请选择城市'],
        backdrop: true,
        backdropClickToClose: true,
        // defaultAreaData: [],
        tag: '-',
        cssClass: 'selectCity',
        iconClass: 'ion-location',
        buttonClicked: function() {
            $scope.useMes.address = vm.CityPickData.areaData.join('-');
            // console.log(vm.CityPickData.areaData);
            // vm.cb();
        },
        // title: '请选择城市'
    };


    //点击注册，生成用户信息
    var isReq = false;
    $scope.addUser = function() {
        // console.log($scope.useMes);
        if(isReq){
            return
        }
        $ionicLoading.show({
            content: 'Loading',
            animation: 'fade-in',
            showBackdrop: false,
            maxWidth: 200,
            showDelay: 0
        });
        isReq = true;
        $http({
            method: 'POST',
            url: $myconfig.api.base_host + '/users/add_user',
            data: $scope.useMes
        }).then(function(res) {
            isReq = false;
            $ionicLoading.hide();
            // console.log(res.data.data);
            if (res.data.success) {
                $scope.success_text = '注册成功，请登录'
                $mydialog.success($scope);
                $state.go('app.login');
            } else {
                $scope.err = res.data.data;
                $mydialog.fail($scope);
            }
        });
    };

    $scope.$on('$ionicView.enter', function() {

        $ionicConfig.views.swipeBackEnabled(false);

    });


});
